﻿using Ldt.DataEngine.DataFlowParse.Model;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.XMLConfigModel.XmlCode;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CommonModule.XmlCodeCommon
{
    /// <summary>
    /// 阶段优化判定模块
    /// </summary>
    public class XmlCodeStartModel
    {
        /// <summary>
        /// 中间数据
        /// </summary>
        public DataContext dataContext { get; set; }
        
        private string SaveUrl = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ldt.elementcenterfilestore");
        
        /// <summary>
        /// 执行配置文件解析
        /// </summary>
        public bool Extract(ConfigModel configModel)
        {
            if (configModel.ConfigDetail != null && configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "moduleconditioncofing") != null)
            {

                dataContext.InteractiveShow.LogShow("存在流程条件配置，进行流程判定");
                bool fag = false;
                XmlDocument configxml = new XmlDocument();
                configxml.LoadXml(configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "moduleconditioncofing").ConfigContent);
                XmlCodeModel xmlCodeModel = XmlUtility.DeserializeToObject<XmlCodeModel>(configxml.OuterXml);
                foreach (var rulemodel in xmlCodeModel.RulemodelList)
                {
                    fag = XmlCodeExt(rulemodel);
                }
                dataContext.InteractiveShow.LogShow("判定结果"+fag.ToString());
                return fag;
            }
            else
            {
                dataContext.InteractiveShow.LogShow("不存在流程优化配置文件。");
                return true;
            }
           
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public XmlDocument Redxml(string type) 
        {
            XmlDocument xmlDocument = new XmlDocument();
            switch (type)
            {
                case "1":
                    xmlDocument = dataContext.DataLayerAns.AnalysisResultsXml;
                    break;
                case "2":
                    if (dataContext.DataLayerAns.ElementAnalysisResults!=null  && dataContext.DataLayerAns.ElementAnalysisResults.Count>0)
                    {
                        xmlDocument = dataContext.DataLayerAns.ElementAnalysisResults.First().Value;
                    }
                    break;
                case "3":
                    xmlDocument = dataContext.DataLayerOpt.OptimizationXml;
                    break;
                case "4":
                    xmlDocument = dataContext.DataLayerOpt.OptimizationXml;
                    break;
                case "5":
                    //xmlDocument = dataContext.DataLayerOpt.OptimizationXml;
                    DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                    An_anjiancunchu anjiananyoucunchu = anjiancunchudal.GetList(dataContext.DataCommon.CaseId, "4").FirstOrDefault();
                    if (anjiananyoucunchu != null)
                    {
                        var anjianList = anjiancunchudal.GetList(dataContext.DataCommon.CaseId, "4").ToList();
                        foreach (var anj in anjianList)
                        {
                            xmlDocument=ReadDataXML(anj.Wenjianid);
                        }
                    }
                    break;

            }
            return xmlDocument;
        }
        
        /// 获取XML数据
        /// </summary>
        /// <param name="id">XMLid</param>
        /// <returns></returns>
        public XmlDocument ReadDataXML(string id)
        {
            XmlDocument xmlDocument = new XmlDocument();
            dynamic message = HttpHelp.HttpGet(SaveUrl + "/api/XmlDataManage/GetXmlContent/" + id, "");
            string messagex = message;
            xmlDocument.LoadXml(messagex.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
            return xmlDocument;
        }
        public bool XmlCodeExt(Rulemodel rulemodel)
        {
            bool fag = false;
            try
            {
               
                Dictionary<string, List<string>> diValue = new Dictionary<string, List<string>>();
                foreach (var element in rulemodel.ElementModelList)
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument = Redxml(element.type);
                    if (xmlDocument==null)
                    {
                        return true;
                    }
                    XmlNodeList xmlNodeList = xmlDocument.SelectNodes(element.Path);
                    if (xmlNodeList != null && xmlNodeList.Count > 0)
                    {
                        List<string> list = new List<string>();
                        foreach (XmlNode node in xmlNodeList)
                        {
                            if (node.Attributes[element.Name] != null)
                            {
                                list.Add(node.Attributes[element.Name].Value);
                            }
                        }
                        if (list.Count > 0)
                        {
                            diValue.Add(element.Cname, list);
                        }

                    }
                    else
                    {
                        List<string> list = new List<string>();

                        diValue.Add(element.Cname, list);
                    }
                }
                foreach (RunleItem runleItem in rulemodel.RunleItemList)
                {

                    fag = RunExt(runleItem, diValue);
                    if (fag)
                    {
                        return fag;
                    }
                }
            }
            catch (Exception ex)
            {
                fag = true;
                dataContext.InteractiveShow.LogShow("加载流程优化错误");
            }
            
            return fag;
        }

        /// <summary>
        /// 执行判定
        /// </summary>
        /// <param name="runleItem"></param>
        /// <param name="diValue"></param>
        /// <param name="xmlDocument"></param>
        /// <returns></returns>
        public bool RunExt(RunleItem runleItem, Dictionary<string, List<string>> diValue)
        {
            if (runleItem.Path != null)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument = Redxml(runleItem.Type);
                List<string> patList = PathExt(diValue, runleItem.Path);
                foreach (string path in patList)
                {
                    XmlNodeList xmlNodeList = xmlDocument.SelectNodes(path);
                    if (!string.IsNullOrEmpty(runleItem.exp))
                    {
                        var regvalue = Regex.Match(runleItem.exp, @"(》|《|》\=|《\=)");
                        if (regvalue != null && !string.IsNullOrEmpty(regvalue.Value))
                        {
                            var numbervlaue = Regex.Match(runleItem.exp, @"\d+");
                            int number = int.Parse(numbervlaue.Value);
                            bool fag = false;
                            switch (regvalue.Value)
                            {
                                case "=":
                                    if (xmlNodeList.Count == number)
                                    {
                                        fag = true;
                                    }
                                    break;
                                case "》":
                                    if (xmlNodeList.Count > number)
                                    {
                                        fag = true;
                                    }
                                    break;
                                case "《":
                                    if (xmlNodeList.Count < number)
                                    {
                                        fag = true;
                                    }
                                    break;
                                case "《=":
                                    if (xmlNodeList.Count <= number)
                                    {
                                        fag = true;
                                    }
                                    break;
                                case "》=":
                                    if (xmlNodeList.Count >= number)
                                    {
                                        fag = true;
                                    }
                                    break;
                            }
                            if (fag)
                            {
                                if (runleItem.Runle != null)
                                {
                                    fag = RunExt(runleItem.Runle, diValue);
                                }
                                else
                                {
                                    return fag;
                                }
                            }
                            if (fag)
                            {
                                return fag;
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(runleItem.Count))
                    {
                        bool fag = false;
                        if (diValue.ContainsKey(runleItem.Count))
                        {
                            if (xmlNodeList.Count==diValue[runleItem.Count].Count)
                            {
                                fag = true;
                            }
                        }
                        if (fag)
                        {
                            if (runleItem.Runle != null)
                            {
                                fag = RunExt(runleItem.Runle, diValue);
                            }
                            else
                            {
                                return fag;
                            }
                        }
                        if (fag)
                        {
                            return fag;
                        }


                    }
                    else if (!string.IsNullOrEmpty(runleItem.NoCount))
                    {
                        bool fag = false;
                        if (diValue.ContainsKey(runleItem.NoCount))
                        {
                            if (xmlNodeList.Count != diValue[runleItem.NoCount].Count)
                            {
                                fag = true;
                            }
                        }
                        if (fag)
                        {
                            if (runleItem.Runle != null)
                            {
                                fag = RunExt(runleItem.Runle, diValue);
                            }
                            else
                            {
                                return fag;
                            }
                        }
                        if (fag)
                        {
                            return fag;
                        }


                    }




                }
            }
            return false;
        }

        /// <summary>
        /// 获取路径组合
        /// </summary>
        /// <param name="dicList">条件实体i</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List<string> PathExt(Dictionary<string, List<string>> dicList, string path)
        {
            List<string> pathList = new List<string>();
            if (dicList == null || dicList.Count == 0)
            {
                pathList.Add(path);
            }
            else
            {
                foreach (var dicvalue in dicList)
                {
                    if (path.IndexOf("{" + dicvalue.Key + "}") > -1)
                    {
                        if (pathList.Count == 0)
                        {
                            foreach (var value in dicvalue.Value)
                            {
                                pathList.Add(path.Replace("{" + dicvalue.Key + "}", value));

                            }
                        }
                        else
                        {
                            List<string> pathTempList = JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(pathList));
                            pathList = new List<string>();
                            foreach (var value in dicvalue.Value)
                            {
                                foreach (var pathtemp in pathTempList)
                                {
                                    pathList.Add(pathtemp.Replace("{" + dicvalue.Key + "}", value));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (path.IndexOf("{")<0 && path.IndexOf("}")<0)
                        {
                            pathList.Add(path);
                        }
                       
                    }
                }
            }
            if (pathList.Count>0)
            {
                pathList= pathList.Distinct().ToList();

            }
            return pathList;
        }


    }

}
